package com.cbd.service.impl;


import com.cbd.dto.UserEmailDto;
import com.cbd.service.IEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * @author BingBing
 * @desc   邮件服务实现类
 * @date 2024/11/21 14:13
 */
@Service
public class EmailServiceImpl implements IEmailService {
    //定义验证码
    private  Integer userVerificationCode = null;

    @Autowired
    JavaMailSender jms;

    //读取配置文件邮箱账号参数
    @Value("${spring.mail.username}")
    private String sender;

    //发送验证码
    @Override
    public String sendEmail(UserEmailDto user) {
        //随机数用作验证
        Integer userVerificationCode = new Random().nextInt(999999);
        try {
            //建立邮件消息
            SimpleMailMessage mainMessage = new SimpleMailMessage();

            //发送者
            mainMessage.setFrom(sender);

            //接收者
            mainMessage.setTo(user.getEmail());

            //发送的标题
            mainMessage.setSubject("邮箱验证");

            //发送的内容
            String msg = "您好！" + user.getEmail() + ",您正在使用邮箱验证，验证码：" + userVerificationCode + "。";
            mainMessage.setText(msg);

            //发送邮件
            jms.send(mainMessage);

            //下面是加入缓存，以便于进行邮箱验证
            this.userVerificationCode = userVerificationCode;

        } catch (Exception e) {
            System.out.println(e.getMessage());
            return ("发送邮件失败，请核对邮箱账号");
        }
        return "验证码已经发送您的邮箱，请前去邮箱查看，验证码是：" + userVerificationCode ;
    }

    @Override
    public String verificationEmail(UserEmailDto user) {
        if (this.userVerificationCode.equals(user.getUserVerificationCode())){
            return "验证成功";
        }
        return "验证失败";
    }
}
